package it.prova.listener;

import it.prova.Consts;
import it.prova.Utility;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.runtime.IPath;

public class MyResourceChangeListener implements IResourceChangeListener
{
	private List<IPath> paths = new ArrayList<IPath>();
	
	@Override
	public void resourceChanged(IResourceChangeEvent event)
	{
		IResourceDelta resourceDelta = event.getDelta();
		
		// a .template file changed
		if(checkChange(resourceDelta))
		{
			for(IPath path: paths)
			{
				Utility.synchOutput(path);
			}
		}
		paths.clear();
	}
	
	private boolean checkChange(IResourceDelta resourceDelta)
	{
		IPath path = resourceDelta.getFullPath();
		
		boolean extensionFound = false;
		if(path != null)
		{
			String extension = path.getFileExtension();
			System.out.println("extension = " + extension);
			if
			(
				(extension != null) && 
				(Consts.TEMPLATE_FILE_EXTENSION.equals(extension))
			)
			{
				extensionFound = true;
				paths.add(path);
			}
		}
		
		IResourceDelta[] children = resourceDelta.getAffectedChildren();
		
		boolean extensionFoundInChildren = false;
		for(int i=0; i<children.length; i++)
		{
			extensionFoundInChildren = (checkChange(children[i]) || extensionFoundInChildren);
		}
		
		return extensionFound || extensionFoundInChildren;
	}
}